import { isFunction } from 'lodash';
import {
  queryPictures,
  like,
  queryFavlist,
  addToFavlist,
  removeFromFavlist,
  queryTargetPictures,
  comment,
} from '../services/picture';

const initialState = {
  pictures: [],
  errorFetchPictures: false,
};

export default {
  namespace: 'picture',

  state: { ...initialState },

  effects: {
    *fetchPictures({ payload }, { call, put }) {
      const response = yield call(queryPictures, payload ? payload.params : {});
      if (response.isRight) {
        yield put({
          type: 'changePictureInfo',
          payload: response.body.data,
        });
        if (isFunction(payload.onSuccess)) {
          payload.onSuccess(response.body.data);
        }
      }
    },
    *fetchFavlist(_, { call, put }) {
      const response = yield call(queryFavlist);
      if (response.isRight) {
        yield put({
          type: 'changePictureInfo',
          payload: response.body,
        });
      }
    },
    *fetchTargetPictures({ payload }, { call, put }) {
      const response = yield call(queryTargetPictures, payload.params);
      if (response.isRight) {
        yield put({
          type: 'changePictureInfo',
          payload: response.body,
        });
      }
    },
    *like({ payload }, { call }) {
      const response = yield call(like, payload.params);
      if (response.isRight) {
        payload.onSuccess();
      }
    },
    *addToFavlist({ payload }, { call }) {
      const response = yield call(addToFavlist, payload.params);
      if (response.isRight) {
        payload.onSuccess();
      }
    },
    *removeFromFavlist({ payload }, { call }) {
      const response = yield call(removeFromFavlist, payload.params);
      if (response.isRight) {
        payload.onSuccess();
      }
    },
    *comment({ payload }, { call }) {
      const response = yield call(comment, payload.params);
      if (response.isRight) {
        payload.onSuccess();
      }
    },
  },

  reducers: {
    changePictureInfo(state, { payload }) {
      return {
        ...state,
        pictures: payload,
        errorFetchPictures: false,
      };
    },
  },
};
